<template>
  <div class="search-container">
    <!-- 顶部搜索栏区域 -->
    <form action="/" class="search-form">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索历史结果区域 -->
    <search-result v-if="isResultShow" :search-text="searchText" />
    <!-- 搜索建议区域 -->
    <search-suggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
    />
    <!-- 搜索历史区域 -->
    <search-history
      v-else
      :search-histories="searchHistories"
      @clearAllDelete="clearAllDelete"
      @search="onSearch"
    />
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import SearchResult from './components/search-result.vue'
import { setItem } from '@/utils/storage'
export default {
  name: 'SearchIndex',
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult,
  },
  props: {},
  data() {
    return {
      searchText: '',
      // 控制搜索结果的显示
      isResultShow: false,
      // 搜索的历史记录数据
      searchHistories: [],
    }
  },
  computed: {},
  watch: {
    searchHistories(value) {
      setItem('TOUTIAO_SEARCH_HISTORIES', value)
    },
  },
  created() {},
  mounted() {},
  methods: {
    onSearch(val) {
      // console.log(val)
      // 更新文本框内容
      this.searchText = val
      // 存储历史记录
      // 重复的历史记录移除掉
      const index = this.searchHistories.indexOf(val)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(val)
      // 搜索渲染结果
      this.isResultShow = true
    },
    onCancel() {
      this.$router.back()
    },
    clearAllDelete() {
      // 删除所有历史记录
      this.searchHistories = []
    },
  },
}
</script>

<style lang="less">
.search-container {
  padding-top: 54px;
  .van-search__action {
    color: #ffffff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>